<?php

namespace app\api\logic;

use app\admin\model\user\UserMember;
use app\basic\BaseLogic;
use app\admin\model\user\Vip;
use app\admin\model\user\UserVipCard;
use think\facade\Db;


class UserVipCardLogic extends BaseLogic
{
    protected $userVipModel;
    protected $vipCardModel;

    protected $error;

    public function __construct()
    {
        $this->model = new UserVipCard();
        $this->userVipModel = $this->model;
        $this->vipCardModel = new Vip();
    }
 /**
     * 处理订单支付后的会员卡开通
     * @param int $orderId 订单ID
     * @param int $userId 用户ID
     * @return bool
     */
    public function handleOrderPaid($orderId, $userId)
    {

        Db::startTrans();
        try {
            // 获取订单信息
            $orderInfo = Db::name('order')->where('order_id', $orderId)->find();
            if (!$orderInfo || $orderInfo['order_type'] != 2) {
                return true;
            }
            // 获取订单商品信息
            $orderGoods = Db::name('order_goods')
                ->where('order_id', $orderId)
                ->find();

            if (!$orderGoods) {
                throw new \Exception("订单商品信息不存在");
            }

            // 获取要开通的会员卡信息
            $newVipCard = $this->vipCardModel->getCardDetail($orderGoods['goods_id']);
            if (!$newVipCard) {
                throw new \Exception("会员卡不存在或已下架");
            }

            // 获取用户现有的所有未过期会员卡
            $userVips = $this->userVipModel->getUserValidVipCards($userId);
            // 处理会员卡开通
            $this->processVipCardActivation($userId, $newVipCard, $userVips, $orderInfo);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 将异常写入日志
            Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }

    /**
     * 处理会员卡开通逻辑
     * @param int $userId
     * @param array $newVipCard
     * @param array $userVips
     * @param array $orderInfo
     */
    protected function processVipCardActivation($userId, $newVipCard, $userVips, $orderInfo)
    {
        $startTime = time();
        $duration = intval($newVipCard['day']);
        if (!empty($userVips)) {
            $highestVip = $userVips[0];
            if ($newVipCard['id'] > $highestVip['vip_card_id']) {
                // 开通更高等级会员卡
                $this->activateHigherLevelCard($userId, $newVipCard, $userVips, $orderInfo, $startTime, $duration);
            } else {
                // 开通同级别或低等级会员卡
                $this->activateLowerOrSameLevelCard($userId, $newVipCard, $userVips, $orderInfo, $duration);
            }
        } else {
            // 首次开通会员卡
            $this->activateFirstCard($userId, $newVipCard, $orderInfo, $startTime, $duration);
        }
    }

    /**
     * 开通更高等级会员卡
     */
    protected function activateHigherLevelCard($userId, $newVipCard, $userVips, $orderInfo, $startTime, $duration)
    {
        // 创建新会员卡记录
        $endTime = $startTime+ $duration * 86400;

        $this->createVipCardRecord([
            'user_id' => $userId,
            'vip_card_id' => $newVipCard['id'],
            'order_no' => $orderInfo['order_no'],
            'discount_number' => $newVipCard['discount'],
            'start_time' => $startTime,
            'end_time' => $endTime,
            'status' => 1
        ]);

        // 更新现有会员卡时间
        foreach ($userVips as $vip) {
            $remainingDays = ceil(($vip['end_time'] - $vip['start_time']) / 86400);
            $newStartTime = $endTime;
            $newEndTime = $newStartTime+ $remainingDays * 86400;
            $this->userVipModel->where('id', $vip['id'])->update([
                'start_time' => $newStartTime,
                'end_time' => $newEndTime,
                'update_time' => time()
            ]);
        }
    }

    /**
     * 开通同级别或低等级会员卡
     */
    protected function activateLowerOrSameLevelCard($userId, $newVipCard, $userVips, $orderInfo, $duration)
    {
        // 查找相同等级的会员卡
        $startTime = null;
        foreach ($userVips as $vip) {
            if ($vip['vip_card_id'] == $newVipCard['id']) {
                $startTime = $vip['end_time'];
                break;
            }
        }

        // 如果没有相同等级卡，则追加到最后
        if (!$startTime) {
            $startTime = end($userVips)['end_time'];
        }

        $endTime = $startTime+ $duration * 86400;

        $this->createVipCardRecord([
            'user_id' => $userId,
            'vip_card_id' => $newVipCard['id'],
            'order_no' => $orderInfo['order_no'],
            'discount_number' => $newVipCard['discount'],
            'start_time' => $startTime,
            'end_time' => $endTime,
            'status' => 1
        ]);
    }

    /**
     * 首次开通会员卡
     */
    protected function activateFirstCard($userId, $newVipCard, $orderInfo, $startTime, $duration)
    {
        $endTime = $startTime + $duration * 86400;
        $this->createVipCardRecord([
            'user_id' => $userId,
            'vip_card_id' => $newVipCard['id'],
            'order_no' => $orderInfo['order_no'],
            'discount_number' => $newVipCard['discount'],
            'start_time' => $startTime,
            'end_time' => $endTime,
            'status' => 1
        ]);
    }

    /**
     * 创建会员卡记录
     * @param array $data
     * @return bool
     */
    protected function createVipCardRecord($data)
    {
        $data['create_time'] = time();
        $data['update_time'] = time();
        return $this->userVipModel->create($data);
    }

    /**
     * 获取用户当前有效的会员信息
     * @param int $userId
     * @return array
     */
    public function getCurrentVipInfo($userId)
    {
        return $this->userVipModel->getUserHighestVipCard($userId);
    }

/**
     * 获取用户会员信息
     * @param int $userId
     * @return array|bool
     */
    public function getVipInfo($userId)
    {
        try {
            // 查询当前会员信息
            $userInfo = (new UserMember())->where("id",$userId)->find();
            if (!$userInfo) {
                return false;
            }
            $userVipInfo = $this->userVipModel->getUserValidVipCards($userId);
            if (!$userVipInfo) {
                return [
                    'is_vip' => false,
                    'nickname' => $userInfo['nickname'],
                    'avatar' => $userInfo['avatar'],
                ];
            }
            $newUserVipInfo = $userVipInfo[0];
            $vipInfo = $this->vipCardModel->getCardDetail($newUserVipInfo['vip_card_id']);
            return [
                'is_vip' => true,
                'vip_id' => $vipInfo['id'],
                'vip_name' => $vipInfo['name'] ?? '',
                'end_time' => date("Y-m-d", $newUserVipInfo['end_time']),
                'status' => $newUserVipInfo['status'],
                'nickname' => $userInfo['nickname'],
                'avatar' => $userInfo['avatar'],
            ];
        } catch (\Exception $e) {
             $this->setError($e->getMessage());
             return false;
        }
    }

    public function setError($error)
    {
        $this->error = $error;
    }

    public function getError()
    {
        return $this->error;
    }


}